﻿using gt.webapi.core.Entity.Common;
using gt.webapi.core.Extensions;
using gt.webapi.core.Repositories;
using System;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace gt.webapi.core.Filters
{
    public class RateLimitFilterAttribute : ActionFilterAttribute
    {
        private IRateLimitRepository m_repository;
        public RateLimitFilterAttribute(IRateLimitRepository repository)
        {
            this.m_repository = repository ?? throw new ArgumentNullException("repository");
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var appkey = actionContext.Request.GetAppKey();
            if (!m_repository.CheckRateLimie(appkey))
            {
                actionContext.Response = new HttpResponseMessage
                {
                    StatusCode = System.Net.HttpStatusCode.Forbidden,
                    Content = new StringContent(Constants.ERRPR_RATE, System.Text.Encoding.UTF8, "text/plain")
                };
            }
            m_repository.IncrementRate(appkey);
            base.OnActionExecuting(actionContext);
        }
    }
}
